#include "../Inc/platform_test.h" 
#include "los_config.h"
#include "los_debug.h"
#include "los_interrupt.h"
#include "los_task.h"
#include "los_tick.h"
#include "../../../../../drivers/framework/include/platform/spi_if.h"
#include "../../../../../drivers/framework/support/platform/include/spi/spi_core.h"
#include "../../Drivers/hdf/spi_stm32l4xx.h"
#include "../../../../../drivers/framework/include/platform/gpio_if.h"
#include "../../../../../drivers/framework/support/platform/include/gpio/gpio_core.h"

extern SPI_HandleTypeDef hspi2;
uint16_t  SPI_FLASH_TYPE=W25Q64;
#define CS_ENABLE() HAL_GPIO_WritePin(GPIOG, GPIO_PIN_8, GPIO_PIN_RESET)
#define CS_DISABLE() HAL_GPIO_WritePin(GPIOG, GPIO_PIN_8, GPIO_PIN_SET) 
static DevHandle Spi2;
const uint8_t TEXT_Buffer[]={"-------------------"};
#define SIZE sizeof(TEXT_Buffer)

struct SpiObject {
    struct SpiCntlr *cntlr;
    uint32_t csNum;
};



void SPI_Flash_Init(void) {
    //断开所有连接的CS片选信号
	GPIO_InitTypeDef GPIO_InitStruct = {0}; 
 
	GPIO_InitStruct.Pin = GPIO_PIN_8;  //SPI CS
 	GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;  // 复用推挽输出
	GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
    HAL_GPIO_Init(GPIOG, &GPIO_InitStruct);
    HAL_GPIO_WritePin(GPIOG, GPIO_PIN_8, GPIO_PIN_SET);

}   
 
void SPI_GPIO_Init(void)
{
  GPIO_InitTypeDef GPIO_InitStruct = {0};

  GPIO_InitStruct.Pin = GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15;
  GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
  GPIO_InitStruct.Pull = GPIO_NOPULL;
  GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
  HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
}

uint16_t SPI_Flash_ReadID(void) {
    uint8_t temp[6];
    uint8_t  pData[6] = {0X90,0,0,0,0xFF,0xFF};
    struct SpiMsg msgs = { pData,temp,6,0,0};
    // CS_ENABLE(); 
    SpiTransfer(Spi2,&msgs, 1);
    msgs.csChange = 1;
    msgs.len = 1;
    msgs.wbuf[0] = 0xFF;
    SpiTransfer(Spi2,&msgs, 1);

    // msgs.wbuf[0] = 0x00;
    // SpiTransfer(Spi2,&msgs, 1); // dummy
    // SpiTransfer(Spi2,&msgs, 1); // dummy
    // SpiTransfer(Spi2,&msgs, 1); // dummy
    // msgs.wbuf[0] = 0xFF;
    // SpiTransfer(Spi2,&msgs, 1);
    // temp[1] = temp[0];
    // SpiTransfer(Spi2,&msgs, 1);
    // HAL_SPI_Transmit(&hspi2, &pData, 1, 0xFFFF); 
    // HAL_SPI_Receive(&hspi2 , temp, 5, 0xFFFF);
    //SPI_HandleTypeDef *hspi, <error-type> *pTxData, <error-type> *pRxData, <error-type> Size, <error-type> Timeout)
    // HAL_SPI_TransmitReceive(&hspi2,pData,temp,6,0XFFFF);
    
    for(uint8_t cnt = 0; cnt < 6; ++cnt) {
        printf("temp[%d] is %x \n", cnt, temp[cnt]);
    }
    
    // CS_DISABLE();

    return  temp[4]<<8 | temp[5];
}

void SPI_Flash_Read(uint8_t* pBuffer,uint32_t ReadAddr,uint16_t NumByteToRead)   
{  
    // uint8_t  pData[4] = {W25X_ReadData,ReadAddr>>16,ReadAddr>>8,ReadAddr};    
    uint8_t len = 4;
    uint8_t wbuf[4] = {W25X_ReadData,ReadAddr>>16,ReadAddr>>8,ReadAddr};
    
    struct SpiMsg msgs = { wbuf,pBuffer,len,1,0,0};

	// CS_ENABLE();                           //使能器件  

    SpiTransfer(Spi2,&msgs, 1);
    msgs.len = 1;
    msgs.csChange = 0;
    for(uint8_t cnt = 0; cnt < NumByteToRead; ++cnt) {
        msgs.wbuf[0] = 0xFF; 
        msgs.rbuf = &pBuffer[cnt];    
        SpiTransfer(Spi2,&msgs, 1);
    }
    msgs.csChange = 1;
    msgs.rbuf = &wbuf[3];  
    SpiTransfer(Spi2,&msgs, 1);

    // HAL_SPI_Transmit(&hspi2, &pData, 4, 0xFFFF);          //·发送读取命令  
    // HAL_SPI_Receive(&hspi2, pBuffer, NumByteToRead, 0xFFFF); 
	// CS_DISABLE();                            //取消片选	      
}


  // HAL_GPIO_WritePin(SPI2_CS_GPIO_Port, SPI2_CS_Pin  , GPIO_PIN_RESET);
  // HAL_GPIO_WritePin(GPIOB,GPIO_PIN_13 | GPIO_PIN_14 | GPIO_PIN_15,GPIO_PIN_RESET);

void SPI_Flash_Test()
{
    struct SpiDevInfo spiinfo={2,STM32L4R9_GPIOG_PIN8};
    uint16_t tmp;
    uint8_t datatemp[SIZE];
    uint32_t FLASH_SIZE1=8*1024*1024;	//FLASH 大小为8M字节
    
    Spi2 = SpiOpen(&spiinfo);

    SPI_Flash_Init();
    SPI_GPIO_Init();

    tmp = SPI_Flash_ReadID();
    while(tmp != 0XEF16) {
        printf("25Q64 Check Failed!%x\n",tmp);
        for(uint32_t cnt = 0x00FFFFFF; cnt >= 1; --cnt);
            printf("Please Check!\n");
        tmp = SPI_Flash_ReadID();
    }
    printf("25Q64 Check success!W25Q64 0XEF16 \n");
    
    while (1)
    {
        printf("Start Read W25Q64.... \n");
        SPI_Flash_Read(datatemp,FLASH_SIZE1-100,SIZE);//从数的第100个地?处开始读出size个字?
        printf("The Data Readed Is:  \n");	// 提示传输完成
        printf("%s",datatemp);					// 显示读到的字符串
        
        HAL_Delay(50);
    }

    // obj1 = (struct SpiObject *)Spi2;
    // stm32xx=obj1->cntlr->priv; 
    // printf("stm32xx address :%x stm32xx->spiHandle->Instance : %x SPI2 %x\n",stm32xx,stm32xx->spiHandle->Instance,SPI2);
}


void GPIO_NormalTest()
{
    uint16_t gpio = 116;
    uint8_t val;
    int32_t ret = GpioSetDir(gpio, GPIO_DIR_IN);
    if (ret != HDF_SUCCESS) {        
        while(1) {
            for(uint32_t cnt = 0x00FFFFFF; cnt >= 1; --cnt);
            printf("set dir error \n");
        }
    }

    // //=========测试一下直接使用HAL的库函数
    // GPIO_InitTypeDef GPIO_InitStruct = {0}; 
    // // __HAL_RCC_GPIOH_CLK_ENABLE();
 
	// GPIO_InitStruct.Pin = GPIO_PIN_4;  //SPI CS
 	// GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;  // 复用推挽输出
    // GPIO_InitStruct.Pull = GPIO_NOPULL;
	// GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    // HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);

    while(1) {
        // //=========测试一下直接使用HAL的库函数
        // HAL_GPIO_WritePin(GPIOH, GPIO_PIN_4, val);
        // ret = GpioWrite(gpio, val);
        // val = ~val & 0x01;

        ret = GpioRead(gpio, &val);
        for(uint32_t cnt = 0x05FFFFFF; cnt >= 1; --cnt);

        printf("hello %u\n",val);
    }


}

int32_t UserDefine_EXTI_IRQHandler(uint16_t gpio, void *data)
{
  /* EXTI line interrupt detected */ 
//   HAL_GPIO_TogglePin(GPIOH,GPIO_PIN_4);
    GpioWrite(gpio, 1);
    printf("exit :%d\n",gpio);
    return 0;
}

void GPIO_ISRTest()
{
    uint16_t gpio = 22;
    uint16_t mode = GPIO_IRQ_TRIGGER_RISING;//GPIO_IRQ_TRIGGER_FALLING
    GpioIrqFunc func = UserDefine_EXTI_IRQHandler;
    uint8_t val;
    
    int32_t ret = GpioSetIrq(gpio, mode, func, NULL);
    GpioEnableIrq(gpio);
    GPIO_InitTypeDef GPIO_InitStruct = {0}; 

    // __HAL_RCC_GPIOB_CLK_ENABLE(); 
	// GPIO_InitStruct.Pin = GPIO_PIN_6;  //SPI CS
 	// GPIO_InitStruct.Mode = GPIO_MODE_IT_RISING ;  // 复用推挽输出 GPIO_MODE_IT_RISING
    // GPIO_InitStruct.Pull = GPIO_NOPULL;
	// GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    // HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
    // /* 配置 EXTI 中断源 到key1 引脚、配置中断优先级*/
    // HAL_NVIC_SetPriority(EXTI9_5_IRQn, 0, 0);
    // /* 使能中断 */
    // HAL_NVIC_EnableIRQ(EXTI9_5_IRQn);
    // __HAL_RCC_GPIOH_CLK_ENABLE();
	// GPIO_InitStruct.Pin = GPIO_PIN_4;  //SPI CS
 	// GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;  // 复用推挽输出
    // GPIO_InitStruct.Pull = GPIO_NOPULL;
	// GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    // HAL_GPIO_Init(GPIOH, &GPIO_InitStruct);
    // HAL_GPIO_WritePin(GPIOH,GPIO_PIN_4,0);

    gpio = 116;
    ret = GpioSetDir(gpio, GPIO_DIR_OUT);
    if (ret != HDF_SUCCESS) {        
        while(1) {
            for(uint32_t cnt = 0x00FFFFFF; cnt >= 1; --cnt);
            printf("set dir error \n");
        }
    }

    while(1) {
        // HAL_GPIO_WritePin(GPIOH, GPIO_PIN_4, 0);
        GpioWrite(gpio, 0);
        // for(uint32_t cnt = 0x009FFFFF; cnt >= 1; --cnt);
        HAL_Delay(150);
    }
}




void  HDF_Init(void)
{

    // __HAL_RCC_GPIOH_CLK_ENABLE();
    if (LOS_KernelInit() != LOS_OK) {
        return;
    }
    printf("entering DeviceManagerStart\n");
    /* HDF ENTRY START */
    printf("HDF ENTRY START\n");
    if (DeviceManagerStart() != 0) {
        printf("HDF START FAIL!\n");
    } else {
        printf("HDF START OK!\n");
    }
}
